#include "ScanCameraControlSDK.h"
#include "SDKInterface.h"
#include "ScanCameraDevice.h"
#include <QDebug>
//SDK的名称
#define SDK_NAME "ScanCameraControlSDK"
//SDK版本
#define SDK_VERSION "1.0.0"

/**
 * @brief ScanCameraControlSDK::ScanCameraControlSDK
 * @param parent 父对象指针
 */
ScanCameraControlSDK::ScanCameraControlSDK(QObject *parent) : ControlModuleSDKInterface(parent)
{

}

/**
 * @brief ScanCameraControlSDK::~ScanCameraControlSDK
 */
ScanCameraControlSDK::~ScanCameraControlSDK()
{
    closeAllDevices();
    qDebug() << "ScanCameraControlSDK destroyed";
}

/**
 * @brief ScanCameraControlSDK::sdkName
 * @return SDK名称
 */
QString ScanCameraControlSDK::sdkName() const
{
    return SDK_NAME;
}

/**
 * @brief ScanCameraControlSDK::SDKVersion
 * @return SDK版本号
 */
QString ScanCameraControlSDK::SDKVersion() const
{
    return SDK_VERSION;
}

/**
 * @brief ScanCameraControlSDK::openDevice
 * @param params 连接参数，通常为串口名称
 * @return 连接成功返回true，失败返回false
 */
bool ScanCameraControlSDK::openDevice(const QVariant& params)
{
    // 假设params是串口名称
    QString portName = params.toString();

    if (portName.isEmpty()) {
        qDebug() << "Invalid serial port name";
        return false;
    }

    // 检查设备是否已经连接
    if (m_deviceMap.contains(portName)) {
        qDebug() << "Device already exists in map:" << portName;
        if (m_deviceMap[portName].pDevice->isConnected()) {
            return true;
        }
        // 如果设备对象存在但未连接，则尝试重新连接
        return m_deviceMap[portName].pDevice->open();
    }

    // 创建新的设备对象
    ScanCameraDevice* device = new ScanCameraDevice(portName, this);

    // 尝试打开设备连接
    bool success = device->open();

    if (success)
    {
        // 将设备添加到映射表
        ScanCameraDeviceInfo deviceInfo;
        deviceInfo.pDevice = device;
        deviceInfo.pParametersWidget = nullptr;
        deviceInfo.pParametersDialog = nullptr;
        m_deviceMap[portName] = deviceInfo;

        qDebug() << "Successfully added device to map:" << portName;
    }
    else
    {
        // 连接失败，删除设备对象
        delete device;
        qDebug() << "Failed to connect to device on port:" << portName;
    }

    return success;
}

/**
 * @brief ScanCameraControlSDK::closeDevice
 * @param params 设备标识参数，通常为串口名称
 */
void ScanCameraControlSDK::closeDevice(const QVariant& params)
{
    // 假设params是串口名称
    QString portName = params.toString();

    if (portName.isEmpty())
    {
        return;
    }

    // 检查设备是否存在
    if (!m_deviceMap.contains(portName))
    {
        return;
    }

    // 获取设备信息
    ScanCameraDeviceInfo& deviceInfo = m_deviceMap[portName];

    // 关闭设备连接
    deviceInfo.pDevice->close();

    // 释放UI组件资源
    if (deviceInfo.pParametersWidget)
    {
        delete deviceInfo.pParametersWidget;
        deviceInfo.pParametersWidget = nullptr;
    }
    if (deviceInfo.pParametersDialog)
    {
        delete deviceInfo.pParametersDialog;
        deviceInfo.pParametersDialog = nullptr;
    }

    delete deviceInfo.pDevice;
    // 从映射表中移除设备并删除
    m_deviceMap.remove(portName);
}

/**
 * @brief 关闭所有设备
 */
void ScanCameraControlSDK::closeAllDevices()
{
    qDebug() << "Closing all scan camera control devices";

    // 遍历映射表，关闭并删除所有设备
    QList<QString> portNames = m_deviceMap.keys();
    for (const QString& portName : portNames) {
        closeDevice(QVariant(portName));
    }

    // 清空映射表
    m_deviceMap.clear();
}

/**
 * @brief ScanCameraControlSDK::searchDevices
 * @param devices 输出参数，用于存储搜索到的设备列表
 * @return 搜索成功返回true，未找到设备返回false
 */
bool ScanCameraControlSDK::searchDevices(QList<QVariant>& devices)
{
    QList<QString> foundDevices = ScanCameraDevice::searchDevices();

    // 将找到的设备添加到输出列表
    for (const QString& deviceInfo : foundDevices)
    {
        devices.append(deviceInfo);
    }

    return !devices.isEmpty();
}

/**
 * @brief 获取快速参数设置widget
 * @param deviceId 设备ID
 * @param parent 父窗口指针
 * @return 快速参数设置界面组件
 */
QWidget *ScanCameraControlSDK::getQuickParametersWidget(const QVariant &deviceId, QWidget *parent)
{
    QString deviceIdStr = deviceId.toString();
    if (!m_deviceMap.contains(deviceIdStr))
    {
        return nullptr;
    }
    ScanCameraDevice* device = m_deviceMap[deviceIdStr].pDevice;

    // 如果参数Widget不存在，则创建一个新的，直接在构造函数中传入设备指针
    if (!m_deviceMap[deviceIdStr].pParametersWidget)
    {
        m_deviceMap[deviceIdStr].pParametersWidget = new ControlModuleParametersWidget(device, parent);
        connect(m_deviceMap[deviceIdStr].pParametersWidget,&ControlModuleParametersWidget::writeLog,this,&ScanCameraControlSDK::writeLog);
        connect(m_pScanControlPresetDialog,&ScanControlPresetDialog::finished,this,[this,deviceIdStr](){
            m_deviceMap[deviceIdStr].pParametersWidget->updateConfig(m_pScanControlPresetDialog->getUIData());
        });
        syncParametersConnect();
    }
    m_coverOpenDevice = deviceId;
    return m_deviceMap[deviceIdStr].pParametersWidget;
}

/**
 * @brief 设置设备触发模式
 * @param deviceId 设备ID
 * @param triggerMode 触发模式，使用TRIGGER_MODE_*宏定义
 * @return 设置成功返回true，失败返回false
 */
bool ScanCameraControlSDK::setDeviceTriggerMode(const QVariant& deviceId, int triggerMode)
{
    if(TRIGGER_MODE_CONTINUOUS==triggerMode)
    {
        return true;
    }
    // 将设备ID转换为字符串（通常是串口名称）
    QString portName = deviceId.toString();
    
    // 检查设备是否存在
    if (!m_deviceMap.contains(portName))
    {
        return false;
    }
    
    // 获取设备对象
    ScanCameraDevice* device = m_deviceMap[portName].pDevice;
    uint8_t scanMode;
    switch(triggerMode)
    {
        case TRIGGER_MODE_EXTERNAL_SINGLE:
        {
            scanMode=0;
        }break;
        case TRIGGER_MODE_EXTERNAL_CONTINUOUS:
        {
            scanMode=2;
        }break;
        case TRIGGER_MODE_INTERNAL:
        {
            scanMode=3;
        }break;
    }

    CommandResult recv = device->setScanMode(scanMode);
    if(scanMode == TRIGGER_MODE_INTERNAL){
        CommandResult x01 = device->triggerScan();
        if(x01 == CommandResult::Success){
            int i = 0 ; i ++;
            qDebug() << __FUNCTION__ << __LINE__;
        }else{
            int i = 0 ; i ++;
            qDebug() << __FUNCTION__ << __LINE__;
        }
    }
    return recv == CommandResult::Success ;
}

bool ScanCameraControlSDK::setDeviceParameters(const QVariant& deviceId, const QVariantMap& params)
{
    // 将deviceId转换为QString
    QString portName = deviceId.toString();
    
    // 检查设备是否存在
    if (!m_deviceMap.contains(portName)) {
        writeLog(QString("设备 %1 不存在").arg(portName), 2, true);
        return false;
    }
    
    // 获取设备实例
    ScanCameraDevice* device = m_deviceMap[portName].pDevice;
    device->setParameters(params);
    return true;
}

bool ScanCameraControlSDK::getDeviceParameters(const QVariant& deviceId, QString& configName, QVariantMap& params)
{
    // 将deviceId转换为QString
    QString portName = deviceId.toString();
    
    // 检查设备是否存在
    if (!m_deviceMap.contains(portName)) {
        writeLog(QString("设备 %1 不存在").arg(portName), 2, true);
        return false;
    }
    
    // 设置配置名称
    configName = "ScanDeviceConfig";
    
    // 获取设备实例
    ScanCameraDevice* device = m_deviceMap[portName].pDevice;
    
    params = device->getParameters();
    return true;
}

bool ScanCameraControlSDK::setPresetParameters(const QVariantMap& params)
{
    m_pScanControlPresetDialog->setUIData(params);
    return true;
}

bool ScanCameraControlSDK::getPresetParameters(QString& configName, QVariantMap& params)
{
    // 设置配置名称
    configName = m_pScanControlPresetDialog->property("ConfigName").toString();
    
    // 获取预设参数
    params = m_pScanControlPresetDialog->getUIData();
    return true;
}

void ScanCameraControlSDK::syncParametersConnect()
{
    if(m_coverOpenDevice.isValid() && !m_coverOpenDevice.toString().isEmpty()){
        QString deviceId = m_coverOpenDevice.toString();
        if(m_deviceMap[deviceId].pParametersDialog && m_deviceMap[deviceId].pParametersWidget){
            connect(m_deviceMap[deviceId].pParametersWidget,&ControlModuleParametersWidget::syncParameters,m_deviceMap[deviceId].pParametersDialog,&SKFunctionSet::onSyncParameters);
            connect(m_deviceMap[deviceId].pParametersDialog,&SKFunctionSet::syncParameters,m_deviceMap[deviceId].pParametersWidget,&ControlModuleParametersWidget::onSyncParameters);

        }
    }
}

/**
 * @brief 获取参数对话框
 * @param deviceId 设备ID
 * @param parent 父窗口指针
 * @return 参数设置对话框
 */
QDialog *ScanCameraControlSDK::getParametersDialog(const QVariant &deviceId, QWidget *parent)
{
    QString deviceIdStr = deviceId.toString();
    if (m_deviceMap.contains(deviceIdStr))
    {
        ScanCameraDevice* device = m_deviceMap[deviceIdStr].pDevice;

        // 如果参数对话框不存在，则创建一个新的，直接在构造函数中传入设备指针
        if (!m_deviceMap[deviceIdStr].pParametersDialog)
        {
            m_deviceMap[deviceIdStr].pParametersDialog = new SKFunctionSet(device, parent);
            connect(m_deviceMap[deviceIdStr].pParametersDialog,&SKFunctionSet::writeLog,this,&ScanCameraControlSDK::writeLog);
            connect(m_pScanControlPresetDialog,&ScanControlPresetDialog::finished,this,[this,deviceIdStr](){
                m_deviceMap[deviceIdStr].pParametersDialog->updateConfig(m_pScanControlPresetDialog->getUIData());
            });
            syncParametersConnect();
        }
        m_coverOpenDevice = deviceId;
        return m_deviceMap[deviceIdStr].pParametersDialog;
    }
    return nullptr;
}

/**
* @brief 获取预设参数对话框
* @param deviceId 设备ID
* @param parent 父窗口指针
* @return 预设参数设置对话框
*/
QDialog *ScanCameraControlSDK::getPresetParametersDialog(QWidget *parent)
{
    if(m_pScanControlPresetDialog)
    {
        m_pScanControlPresetDialog=new ScanControlPresetDialog(parent);
    }
    return m_pScanControlPresetDialog;
}

